<template>
  <div class="main">
    <!-- <div>搜索框</div> -->
    <el-form>
      <el-form-item>
        <el-input v-model.trim="inputValue" placeholder="请输入内容"></el-input>
      </el-form-item>
      <div><el-button type="primary" @click="handleClick">搜索</el-button></div>
      <div class="cbtn">
        <el-button type="success" @click="createClick">增加</el-button>
      </div>
    </el-form>
    <!-- Table组件 -->
    <Table
      :list="courseList"
      :editClick="editClick"
      :deleteHandle="deleteHandle"
    />
    <Pagination
      :currentChange="currentChange"
      :currentPage="data.page"
      :pagesize="data.size"
      :total="data.total"
    />
    <div @click="goTest"></div>
  </div>
  <!-- 
       v-if : 当点击编辑按钮时 组件才进行渲染 而v-show 是页面一开始(刷新)就渲染,在点击只是将它展现出来 里面的数据并未赋上值
  -->
  <EditPop
    :popShow="popShow"
    v-if="popShow"
    :message="courseItemState.message"
    :confirmClick="confirmClick"
  />
  <CreatePop
    :createPopShow="createPopShow"
    v-if="createPopShow"
    :confirmCreateClick="confirmCreateClick"
  />
</template>
<script setup>
import Table from './Table.vue';
import EditPop from './EditPop.vue';
import CreatePop from './CreatePop.vue';

import Pagination from './Pagination.vue';

import { onMounted, reactive, ref } from 'vue';
import { computed } from '@vue/reactivity';
// import { getCourse } from '../api/index';
// import { getUpdateCourse } from '../api/index';
// import { getDeleteCourse } from '../api/index';
// import { getCreateCourse } from '../api/index';
import router from '../router/index'

import * as api from '../api/index';
import emitter from '../utils/eventBus';

/**
 * 初始化的数据
 */

const data = reactive({
  list: [],
  page: 1, //默认展示第一页
  total: '', //数据的总数
  sideCategory: 'front',
  size: 3, //每页展示的数据条数
});

const goTest = () => {
  router.push('/test');
};

/**
 * 获取课程列表数据 课程类别切换逻辑
 */

const getCourseData = async (query) => {
  // 若query存在则为前面的否则为后面的默认值
  const category = query?.category || data.sideCategory;
  const page = query?.page || 1;
  const size = query?.size || data.size;
  const res = await api.getCourse({
    category: category,
    page: page,
    size: size,
  });
  data.list = res?.list.filter((item) => {
    // 筛选符合分类的课程
    return item.category === category;
  });
  data.total = res?.total;
  // console.log('data.total', data.total);
};
/**
 * 监听课程类目tab切换 course 是事件名 type是参数
 */
onMounted(() => {
  getCourseData();
  emitter.on('course', (category) => {
    data.page = 1;
    data.sideCategory = category;
    getCourseData({
      category: category,
      page: 1,
    });
  });
});

/**
 * 分页的逻辑
 */
const currentChange = (val) => {
  if (val === 'pre') {
    // 当前页码需大于1
    if (data.page > 1) {
      data.page--;
    } else {
      ElMessage({
        message: '当前已经是第一页',
        type: 'warning',
        showClose: true,
      });
    }
  } else if (val === 'next') {
    // 当前页码需小于最大页
    if (data.page < Math.ceil(data.total / data.size)) {
      // ceil 向下取整 比如总数 是 13 13/5 = 2.6 = 3 则是三页
      data.page++;
    } else {
      ElMessage({
        message: '已经是最后一页',
        type: 'warning',
        showClose: true,
      });
    }
  } else {
    data.page = val;
  }

  //TODO: 调用分页查询的接口
  getCourseData({
    category: data.sideCategory,
    page: data.page,
    size: data.size,
  });
};

/**
 * 搜索框的逻辑开发
 */
const inputValue = ref('');
// 搜索的逻辑
const courseList = computed(() => {
  // ? 的作用是防止 data.list为空
  return data.list?.filter((item) => {
    // 方法可返回某个指定的字符串值在字符串中首次出现的位置 不存在 indexOf的返回值是 -1
    // 若当前项的标题在 我们输入的文本中存在则添加该项
    return item.title.indexOf(inputValue.value) >= 0;
  });
});
// 搜索的按钮
const handleClick = () => {
  if (inputValue.value) {
    ElMessage({
      message: '查询成功',
      type: 'success',
    });
  } else {
    ElMessage({
      message: '请输入搜索内容',
      type: 'error',
    });
  }
};

/**
 * 课程编辑的逻辑
 */
// 编辑的数据 从Table.vue中获得传给EditPop.vue
const courseItemState = reactive({
  message: {},
});

//用于控制编辑对话框的展示
const popShow = ref(false);
// 控制弹窗展示的方法
const isShowPop = (show) => {
  popShow.value = show;
};

// 编辑的按钮
const editClick = (val) => {
  courseItemState.message = val;
  isShowPop(true);
  // console.log(val);
};

/**
 * 取消和确认按钮的逻辑
 */

const confirmClick = (val) => {
  if (val === 'cancel') {
    isShowPop(false);
  } else if (
    val.title != courseItemState.message.title ||
    val.price != courseItemState.message.price
  ) {
    // 数据发生更改
    data.list.map((item) => {
      if (item.id == val.id) {
        item.title = val.title;
        item.price = val.price;
      }
    });
    // TODO: 课程修改接口的调用
    getUpdate(val);

    isShowPop(false);
  } else {
    ElMessage({
      showClose: true,
      message: '没有作出更改',
      type: 'warning',
    });
  }
};

const getUpdate = async (query) => {
  const res = await api.getUpdateCourse({
    id: query.id,
    title: query.title,
    price: query.price,
  });
  console.log('2', res);
  ElMessage({
    message: res.message,
    type: 'success',
    showClose: true,
  });
};

/**
 * 课程添加逻辑开发
 */
// TODO: 课程添加逻辑开发
const createPopShow = ref(false);
const isShowCreatePop = (show) => {
  createPopShow.value = show;
};
const createClick = () => {
  isShowCreatePop(true);
};

const confirmCreateClick = (val) => {
  if (val === 'cancel') {
    isShowCreatePop(false);
  } else {
    isShowCreatePop(false);
    //TODO: 调用后台课程添加接口
    getCreate(val);
  }
};

const getCreate = async (val) => {
  const res = await api.getCreateCourse({
    title: val.title,
    course_img: val.course_img,
    price: val.price,
    point: val.point,
    category: val.category,
  });
  getCourseData({
    category: data.sideCategory,
    page: data.page,
    size: data.size,
  });
};

/**
 * 删除逻辑的开发
 */

const deleteHandle = (val) => {
  //console
  console.log(val);

  if (val) {
    data.list = data.list.filter((item) => {
      return item.id !== val; // 不相等的不会留在新的数组里面 达到一个过滤的效果
    });

    //TODO: 删除接口的调用
    getDelete(val);
  }
};

const getDelete = async (query) => {
  const res = await api.getDeleteCourse({
    id: query,
  });
  ElMessage({
    message: res.message,
    type: 'success',
    showClose: true,
  });
  // 如果当前页数据清空时,应跳转到前一页
  if (data.list.length == 0 && data.page > 1) {
    getCourseData({
      category: data.sideCategory,
      page: data.page - 1,
      size: data.size,
    });
  }
};
</script>
<style lang="less" scoped>
.el-form {
  display: flex;
}
.cbtn {
  margin-left: 15px;
}

.main {
  background-color: #fff;
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;

  .input-with-select {
    width: 400px;
    margin-bottom: 40px;
  }
}

// 表_头部
:deep(.el-table__header-wrapper) {
  position: fixed;
  z-index: 20;
}
// el-table__inner-wrapper.el-table__header-wrapper
// el-table__inner-wrapper.el-table__body-wrapper
// 表__内部
:deep(.el-table__inner-wrapper) {
  overflow: hidden; //清除浮动
}
// 修改正文样式
:deep(.el-table__body-wrapper) {
  margin-top: 40px;
}
// 输入框内部
:deep(.el-input__inner) {
  width: 200px;
  margin-right: 10px;
}

:deep(.el-form-item) {
  margin-right: 10px;
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
  height: 140px !important;
  background-color: #f0f9eb;
}

:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
  height: 140px !important;
  background-color: #f0f9eb;
}

.table {
  height: 80vh;
  width: 85vw;
  overflow: hidden;
  overflow-y: scroll;
}
// 隐藏滚动条
.table::-webkit-scrollbar {
  display: none;
}
</style>
